//
//  GS_OSSManager.m
//  OSS
//
//  Created by 巩小鹏 on 2019/6/25.
//  Copyright © 2019. All rights reserved.
//

#import "GS_OSSManager.h"
#import <AliyunOSSiOS/OSSService.h>

typedef void(^MyBlockComplete)(NSString *imageUrl);
typedef void(^MyBlockError)(NSError *error);

@interface GS_OSSManager ()
{
    MyBlockComplete myBlockComplete;
    MyBlockError myBlockError;

}
/** OSSClient  */
@property(nonatomic,strong)OSSClient *client;
/** endpoint  */
@property(nonatomic,strong)NSString *endpoint;
/** accessKey  */
@property(nonatomic,strong)NSString *accessKey;
/** secretKey  */
@property(nonatomic,strong)NSString *secretKey;
/** bucketName  */
@property(nonatomic,strong)NSString *bucketName;

@end

@implementation GS_OSSManager

+(GS_OSSManager *)sharedManager
{
    static GS_OSSManager *manager=nil;
    static dispatch_once_t once;
    dispatch_once(&once ,^
                  {
                      if (manager==nil)
                      {
                          manager=[[GS_OSSManager alloc]init];
                      }
                  });
    return manager;
}
- (id)init {
    if (self = [super init]) {
        //默认参数:（必传）
        self.endpoint = @"https://oss.qiyiyeye.com";
        self.accessKey = @"LTAI0p4xEmr1LLm0";
        self.secretKey = @"bVnG7DUJHOWMJgYz035fcO3Ut74pzU";
        self.bucketName = @"qy-outlet-001";
    }
    return self;
}
//============================================= File ====================================================

//自定义头像地址
- (NSString *)newFileHeadimag{
    return @"images/yeyewang/headicon/";
}
//自定义头售后图片地址
- (NSString *)newFileAftersalePic{
    return @"images/yeyewang/AftersalePic/";
}
//上传头像接口
- (void)headimg_uploadImgToOssImgPicName:(NSString *)picName imgData:(NSData *)imgData complete:(void (^)(NSString * imgUrl))complete failed:(void (^)(NSError * error))failed{
    NSString * fileName = [NSString stringWithFormat:@"%@%@",[self newFileHeadimag],picName];
    [self uploadImgToOssImgfileName:fileName imgData:imgData complete:complete failed:failed];
}
//申请退货接口
- (void)aftersalePic_uploadImgToOssImgPicName:(NSString *)picName imgData:(NSData *)imgData complete:(void (^)(NSString * imgUrl))complete failed:(void (^)(NSError * error))failed{
    NSString * fileName = [NSString stringWithFormat:@"%@%@",[self newFileAftersalePic],picName];
    [self uploadImgToOssImgfileName:fileName imgData:imgData complete:complete failed:failed];
}

/**
 
 |*** 上传图片总入口 ***|
  上传图片到oss服务器上
 
 @param fileName 自定义的图片文件名
 @param imgData 图片Data数据
 @param complete 返回图片地址
 @param failed  返回error信息
 */
-(void)uploadImgToOssImgfileName:(NSString *)fileName imgData:(NSData *)imgData complete:(void (^)(NSString * imgUrl))complete failed:(void (^)(NSError * error))failed{
    [self uploadImgToOssImgFileName:fileName imgData:imgData];
    myBlockComplete = ^(NSString *imageUrl){
        complete(imageUrl);
    };
    myBlockError = ^(NSError *error){
        failed(error);
    };
}

//=======================================================================================================
/**
 创建初始化oss客户端
 @return oss客户端
 */
-(OSSClient *)client{
    if (_client == nil) {
        
        //明文设置client
        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc]initWithPlainTextAccessKey:self.accessKey secretKey:self.secretKey];

        //初始化client
        _client = [[OSSClient alloc] initWithEndpoint:self.endpoint credentialProvider:credential];
    }
    
    return _client;
}

/**
 上传图片到oss服务器上
 
 @param imgFileName 自定义的图片文件名，名字可以随意写，后缀名不能缺少，切记每次图片名都唯一
 @param imgData 图片Data数据
 */
- (void)uploadImgToOssImgFileName:(NSString *)imgFileName imgData:(NSData *)imgData{
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    // 必填字段
    put.bucketName = self.bucketName;
    //    put.objectKey = @"sales/ios01.png";
    put.objectKey = [NSString stringWithFormat:@"%@.jpeg",imgFileName];
    
    put.uploadingData = imgData;
    
    // 可选字段，可不设置
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [self.client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        
        if (!task.error) {
            NSLog(@"task = %@",task.result);
            NSLog(@"upload object success!");
            //获取图片地址
            [self getImgAddress:imgFileName];
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
            if(myBlockError){
                myBlockError(task.error);
            }
        }
        return nil;
    }];
}
/**
 获取oss上的图片url地址
 
 @param imgFileName imgFileName 图片文件名
 @return 返回图片的url地址
 */
- (NSString *)getImgAddress:(NSString *)imgFileName{
    
    NSString *objectKey = [NSString stringWithFormat:@"%@.jpeg",imgFileName];
    
    NSString * publicURL = nil;
    
    // sign public url
    OSSTask *task = [self.client presignPublicURLWithBucketName:self.bucketName
                                                  withObjectKey:objectKey];
    if (!task.error) {
        publicURL = task.result;
        if(myBlockComplete){
            myBlockComplete(publicURL);
        }
    } else {
        NSLog(@"sign url error: %@", task.error);
        if(myBlockError){
            myBlockError(task.error);
        }
    }
    
    return publicURL;
}
@end
